#!/usr/bin/env python
# coding=utf-8
# Author:  vavava
# Created: 04/11/2012

if __name__ == '__main__':
    """ for file debug"""
    import sys,os
    sys.path.insert(0,os.path.join( os.getcwd(), '..' ))

import time,socket
from vavava.basethread import BaseThread
from taskclient_interface import BaseCommand
from socketserver import TCPServer,StreamRequestHandler
from vavava.workqueue import Work

class SerReqHandler(StreamRequestHandler):
    def __init__(self, request, client_address, server):
        StreamRequestHandler.__init__(self, request, client_address, server)
        self.log = server.log

    def setup(self):
        self.connection = self.request
        if self.timeout is not None:
            self.connection.settimeout(self.timeout)
        if self.disable_nagle_algorithm:
            self.connection.setsockopt(socket.IPPROTO_TCP,
                socket.TCP_NODELAY, True)
        self.rfile = self.connection.makefile('rb', self.rbufsize)
        self.wfile = self.connection.makefile('wb', self.wbufsize)

    def handle(self):
        data = self.rfile.read()
        cmd = BaseCommand.parse(data)
        self.log.debug("New cmd coming: %s %f"%(cmd.name,time.clock()))

        self.server.processor()
    def finish(self):
        print("finish")

class MyTCPServer(TCPServer):
    def __init__(self, dispatcher, server_address,
                 RequestHandlerClass, bind_and_activate=True, log=None):
        TCPServer.__init__(self,server_address,
            RequestHandlerClass,bind_and_activate)
        self.dispatcher = dispatcher
        self.log = log

class ServerInterface(BaseThread):

    def __init__(self, processor, host="localhost",
                 port=4444, timeout= 30, log=None):
        BaseThread.__init__(self,"ServerInterface",log)
        self.host = host
        self.port = port
        self.timeout = timeout
        self.server = None
        self.processor = processor

    def StopServer(self):
        self.running_stop()
        if self.server:
            self.server.shutdown()
        self.join(30)

    def StartServer(self):
        self.running_start()

    def run(self):

        while self.IsRunning:
            try:
                if self.server is None:
                    self.server = MyTCPServer( self.dispatcher,
                        (self.host,self.port), SerReqHandler, log=self.log)
                    self.server.timeout = self.timeout
                    self.server.allow_reuse_address = True
                    self.log.debug("tcp server started")
                    self.server.serve_forever()
            except Exception as e:
                self.log.debug("tcp server stopped")
                self.log.exception(e)
            finally:
                if self.server:
                    self.server.shutdown()
                    self.server = None


# test 000000000000000000000000000000000000000000000000000000000

def test(server):
    server.StartServer()

def main():
    server = ServerInterface(port=55555)
    try:
        test(server)
        while True:
            time.sleep(0.5)
    except(KeyboardInterrupt):
        print('main thread(%f):stop'%time.clock())
        server.StopServer()
        print('main thread(%f):stopped'%time.clock())

if __name__ == '__main__':
    main()

